package com.chj.producer_balance.backupexchange;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者——绑定备用交换器队列的消费者
 */
public class BackupExConsumer {
    public static void main(String[] argv)throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
//        connectionFactory.setVirtualHost("chj_vhost");
//        connectionFactory.setUsername("chj");
//        connectionFactory.setPassword("123456");
        // 打开连接和创建频道，与发送端一样
        Connection connection = connectionFactory.newConnection();
        final Channel channel = connection.createChannel();
        channel.exchangeDeclare(BackupExProducer.BAK_EXCHANGE_NAME, BuiltinExchangeType.FANOUT, true, false, null);
        // 声明一个队列
        String queueName = "fetchother";
        channel.queueDeclare(queueName,false,false,false,null);
        channel.exchangeBind(queueName,BackupExProducer.BAK_EXCHANGE_NAME,"#");
        System.out.println(" [*] Waiting for messages......");
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Received["+envelope.getRoutingKey() +"]"+message);
            }
        };
        // 消费者正式开始在指定队列上消费消息
        channel.basicConsume(queueName,true,consumer);
    }

}
